# -*- coding: utf-8 -*-
# @Time    : 2016/9/18
from sympy import integrate, Interval
from mathsolver.functions.base.base import BaseFunction, new_latex
from mathsolver.functions.base.objects import BaseNumber, BaseIntegral, BaseEq
from mathsolver.functions.hanshu.qujueduizhi import QuJueDuiZhi


class HanShuDingJiFen(BaseFunction):
    """
    函数定积分的计算
    {∫}^{2}_{-2}|{e}^{x}-1|dx=().
    """
    def solver(self, *args):
        eq = args[0].equation
        if 'Abs' in str(eq):
            return JueDuiZhiHanShuJiFen().solver(args[0])
        else:
            return JiBenHanShuDingJiFen().solver(args[0])


class JiBenHanShuDingJiFen(BaseFunction):
    """基本函数定积分的计算"""
    def solver(self, *args):
        integral = args[0]
        eq, variable, upper, lower = integral.equation, integral.var, integral.upper_bound, integral.lower_bound

        # 推导步骤
        t = integrate(eq, variable)
        s = r"\left(" + new_latex(t) + r"\right)" if eq.is_Add else new_latex(t)

        intermediate1 = "\\left." + s + r"\right|_{{{lower}}}^{{{upper}}}" \
            .format(lower=new_latex(lower), upper=new_latex(upper))
        intermediate2 = new_latex(t.subs(variable, upper)) + " - " + new_latex(t.subs(variable, lower))

        result = integrate(eq, (variable, lower, upper))

        self.steps.append(["{0} = {1} = {2} = {3}"
                          .format(integral.printing(), intermediate1, intermediate2, new_latex(result)), ""])
        self.output.append(BaseNumber(result))
        self.label.add("基本函数定积分的计算")

        return self


class JueDuiZhiHanShuJiFen(BaseFunction):
    """绝对值函数定积分的计算"""
    def solver(self, *args):
        integral = args[0]
        eq, var, lower, upper = integral.equation, integral.var, integral.lower_bound, integral.upper_bound
        huajian = QuJueDuiZhi().solver(BaseEq(["y", eq]), Interval(lower, upper, True, True))

        result = 0
        intermediate1 = []
        intermediate2 = []
        for expression, interval in huajian.output:
            low, up = interval.start, interval.end

            # 推导步骤
            intermediate1.append(BaseIntegral(expression, (var, low, up)).printing())
            t = integrate(expression, var)
            s = r"\left(" + new_latex(t) + r"\right)" if expression.is_Add else new_latex(t)
            intermediate2.append("\\left." + s + r"\right|_{{{lower}}}^{{{upper}}}"
                                 .format(lower=new_latex(low), upper=new_latex(up)))

            result += integrate(expression, (var, low, up))

        self.steps.append(["{} = {} = {} = {}".format(integral.printing(),
                                                      " + ".join(intermediate1),
                                                      " + ".join(intermediate2),
                                                      new_latex(result)), ""])

        self.output.append(BaseNumber(result))
        self.label.add("绝对值函数定积分的计算")
        return self


if __name__ == '__main__':
    pass
